/*
 * @description: Ajax_ES5_面向对象封装
 * @author: 宫晓辉
 * @update: 20190122
 */	
function Ajax() {
	this.xhr = new XMLHttpRequest()  //ajax对象
	this.domain = 'http://localhost/'    //此处需要修改
}

/* Object.assign()为对象合并方法,可以将多个对象合并 */
/* Object.assign不支持IE浏览器 */
Object.assign(Ajax.prototype,{
	/* get方法，可直接调用Ajax.get() */
	get:function(url,data,response,timeout){
		this.xhr.timeout = timeout || 999999
		this.xhr.open('GET',this.domain+url+'?'+this.params(data),true)
		this.xhr.send(null)
		var _this = this
		this.xhr.onreadystatechange = function(){
			if(_this.xhr.readyState==4){
				response(_this.resfn(_this.xhr))
			}
		}
	},
	
	/* post方法，可直接调用Ajax.post() */
	post:function(url,data,response,timeout){ 
		this.xhr.timeout = timeout || 999999
		this.xhr.open('POST',this.domain+url,true)
		if(data.constructor.name != 'FormData'){	//如果是上传文件用的FormData就不设置请求头
			this.xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
		}
		this.xhr.send(data.constructor.name == 'FormData'?data:this.params(data))
		var _this = this
		this.xhr.onreadystatechange = function(){
			if(_this.xhr.readyState==4){
				response(_this.resfn(_this.xhr))
			}
		}
	},
	
	/* 请求数据转换为query格式 */
	params:function(data){
		var arr = []
		for(var prop in data){
			arr.push(prop + "=" + data[prop])
		}
		return arr.join("&")
	},
	
	/* 请求回调 */
	resfn:function(xhr) {
		if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
			return {status:xhr.status,data:xhr.responseText}
		}else{
			throw new Error(xhr.status+':服务器请求失败！')
		}
	}
	
	/* jsonp方法，可直接调用Ajax.jsonp() */
	jsonp:function(url,data,response,timeout){
		timeout = timeout || 999999
		var isRes = 0
		let timer = setTimeout(()=>{
				isRes = 1
				throw new Error('请求超时！')
			},timeout)
		let arr = []
		data.cbkey = data.cbkey || 'callback'
		data.callback = data.callback || 'jsonp_cb_' + Date.now()
		for (let key in data) {
			if(key!='cbkey' && key!='callback'){
				arr.push(key + '=' + data[key])
			}
		}
		let parames = arr.join('&') , newScript = document.createElement('script')
		newScript.src = this.domain+url+'?'+ data.cbkey + '=' + data.callback + '&' + parames
		document.body.appendChild(newScript)
		window[data.callback] = res=>{
			clearTimeout(timer)
			if(isRes == 0){
				response(res)
				delete window[data.callback]  //删除对象
				document.body.removeChild(newScript)  //删除创建的内容
			}else{
				delete window[data.callback]  //删除对象
				document.body.removeChild(newScript)  //删除创建的内容
			}
		}
	}
})

/* 使用 */
//new Ajax()

/* 捕获错误 */
/* try{
  //...
}catch(err){
	//...
} */